package com.ruoyi.system.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.rabbitmq.client.Channel;
import com.ruoyi.common.core.constant.ActivityConstant;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.constant.SigninConstants;
import com.ruoyi.common.core.constant.SigninRuleConstants;
import com.ruoyi.common.core.exception.GlobalException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteOssService;
import com.ruoyi.system.domain.SigninRule;
import com.ruoyi.system.service.ISigninRuleService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Lazy(value = false)
@Component
@RabbitListener(queues = {"signQueue"})
public class RabbitListenerSignQueue {

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Autowired
    RemoteOssService remoteOssService;

    @Autowired
    ISigninRuleService signinRuleService;

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;



    @RabbitHandler
    public void lsitenSignQueue(Map<String,Object> map, Channel channel, Message message) throws IOException {

        try{
            insert(map);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
            e.printStackTrace();
        }
    }

    private void insert(Map<String,Object> map){
        String fileName=(String) map.get("fileName");
        Integer activityId=(Integer) map.get("activityId");
        Map<String,Map<String,Object>> signinRuleMap = (Map<String, Map<String, Object>>) map.get("signinRule");
        SigninRule signinRule = JSONObject.parseObject(JSON.toJSONString(signinRuleMap), SigninRule.class);
        BeanUtils.copyBeanProp(signinRule,signinRuleMap);
        boolean f= (boolean) map.get("f");
        if (f){
            String in= (String) map.get("in");
            AjaxResult ajaxResult = remoteOssService.upFile(in, fileName,SecurityConstants.INNER);
            if (ajaxResult.isError()){
                throw new GlobalException("com.ruoyi.system.listener.RabbitListenerSignQueue#lsitenSignQueue异常,请联系管理员处理!");
            }
        }

        //先查有没有,如果有就更新,没有就插入
        SigninRule prule = new SigninRule();
        prule.setActivityId(Long.parseLong(Integer.toString(activityId)));
        prule.setType(signinRule.getType());
        List<SigninRule> signinRules = signinRuleService.selectSigninRuleList(prule);
        //
        signinRule.setPf2(String.valueOf(SecurityUtils.getUserId()));
        signinRule.setUpdateTime(DateUtils.getNowDate());
        //状态刚创建,可用
        signinRule.setPf3(SigninRuleConstants.CREATE_STATUS);




        if (signinRules.size()==0){
            signinRuleService.insertSigninRule(signinRule);
        }else{
            SigninRule rule = signinRules.get(0);
            signinRule.setId(rule.getId());
            signinRule.setType(rule.getType());
            signinRuleService.updateSigninRule(signinRule);
        }

        //在未来某个时间修改该状态表示超时不能用
        //取规则最近一次更新的时间与时长的时间戳相加为结束时间
        Date updateTime = signinRule.getUpdateTime();
        long l2 = updateTime.getTime() + signinRule.getTimeLong() * 60 * 1000;
        Date date = new Date(l2);
        threadPoolTaskScheduler.schedule(new Runnable() {
            @Override
            public void run() {
                //修改状态,表示签到结束
                SigninRule rule = new SigninRule();
                rule.setActivityId(signinRule.getActivityId());
                rule.setPf3(SigninRuleConstants.FATAL_STATUS);
                signinRuleService.updateSigninRule(rule);
                //将redis里的签到状态删除

            }
        },date);
    }
}
